package cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frwidget.CustomStatusView;
import com.mifengkong.frwidget.PercentLinearLayout;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.moxie.client.model.MxParam;

import java.util.Map;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.bean.identify.MailAndFundVerifyDataBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.model.identify.CreditCardVerificateGetResultDataModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem.status.StatusForNonCompliantActivity;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem.status.StatusForNotFoundMailActivity;
import cn.rongdao.jrkabao.ui.loan.LoanCommitActivity;

/**
 * Created by jiangyongxing on 2017/9/19.
 * 描述：
 */

public class IdentificationWithCreditCardActivity extends IdentificationWithValidationItemActivity {

    private static final String VERIFY_TYPE_CREDIT_CARD = "1";
    private static final String VERIFY_TYPE_ONLINE_BANK = "7";
    public static final int SUCCESS_RETURN_DATA_IMPORT = 101;

    @BindView(R.id.aivwvi_checking_pll)
    PercentLinearLayout mLoadingPll;
    @BindView(R.id.aivwvi_loading_imageview)
    CustomStatusView mCustomStatusView;
    @BindView(R.id.aivwvi_checking_tip)
    TextView mLoadingTip;

    private String mCateId;
    private String mProductId;
    private String mPageSource;

    private Map<String, String> loopNeedDataMap = new ArrayMap<>();
    private String mLoanName;

    public static void start(Context context, String cateId, String productId, String pageSource, String loanName) {
        Bundle bundle = new Bundle();
        bundle.putString(InfoConstant.CATE_ID, cateId);
        bundle.putString(InfoConstant.PRODUCT_ID, productId);
        bundle.putString(InfoConstant.PAGE_SOURCE, pageSource);
        bundle.putString(InfoConstant.LOAN_NAME, loanName);
        FRStartActivity.start(context, IdentificationWithCreditCardActivity.class, bundle);
    }

    public static void start(Context context, String cateId, String productId, String loanName) {
        start(context, cateId, productId, InfoConstant.PAGE_SOURCE_DEFAULT, loanName);
    }

    @Override
    protected void initView() {
        super.initView();
        initMXData();
        mCateId = getIntent().getStringExtra(InfoConstant.CATE_ID);
        mProductId = getIntent().getStringExtra(InfoConstant.PRODUCT_ID);
        mPageSource = getIntent().getStringExtra(InfoConstant.PAGE_SOURCE);
        mLoanName = getIntent().getStringExtra(InfoConstant.LOAN_NAME);
        initLoopNeedData();
        mValidationItemUIComponent.setTitle("第二步  信用卡验证");
        titleBarUIComponent.initTitleBlack("信用卡验证");
        mValidationItemUIComponent.setContent(R.drawable.icon_mail, "登录邮箱", "请选择您接收信用卡账单的邮箱");
        mLoadingTip.setText("正在验证信用卡账单\n请稍候...");
        mValidationItemUIComponent.setSubmitOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startMXActiity();
            }
        });

    }


    private void showOnLineBankDialog() {
        new FRDialog.MDBuilder(this)
                .setMessage("检测到为招商银行简版账单，是否去网银导入账单？")
                .setNegativeContentAndListener("否", new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        startLoanCommitActivity();
                        finish();
                        return true;
                    }
                })
                .setNegativeTextColor(ContextCompat.getColor(thisActivity(), R.color.c333333))
                .setPositiveTextColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary))
                .setPositiveContentAndListener("是", new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        loopNeedDataMap.put("verify_type", VERIFY_TYPE_ONLINE_BANK);
                        moXieManager.initOnlineBankingMoXieContent("CMB");
                        startMoxieActivity();
                        return true;
                    }
                })
                .show();
    }

    void startLoanCommitActivity() {
        if (!TextUtils.isEmpty(mCateId) && !TextUtils.isEmpty(mProductId))
            LoanCommitActivity.startWithOtherJump(thisActivity(), InfoConstant.PETTY_LOAN_CATE_ID, mProductId, mPageSource, mLoanName);
    }

    void startMXActiity() {
        loopNeedDataMap.put("verify_type", VERIFY_TYPE_CREDIT_CARD);

        startMoxieActivity();
    }

    private void initLoopNeedData() {
        loopNeedDataMap.put("edition", "381");//3.8.1版本的特殊要求
        if (!TextUtils.isEmpty(mCateId)) {
            loopNeedDataMap.put("cate_id", FRString.valueOf(mCateId));
        } else {
            loopNeedDataMap.put("cate_id", InfoConstant.CREDIT_CATE_ID);
        }
        if (!TextUtils.isEmpty(mProductId)) {
            loopNeedDataMap.put("product_id", FRString.valueOf(mProductId));
        }

    }

    private void initMXData() {
        moXieManager.initMoXieContent(MxParam.PARAM_TASK_EMAIL);
    }

    @Override
    protected void successReturn() {
        super.successReturn();
        mLoadingPll.setVisibility(View.VISIBLE);
        mCustomStatusView.loadLoading();
    }

    @Override
    protected void baseLooperMethod() {
        super.baseLooperMethod();
        CreditCardVerificateGetResultDataModel.getInstance().execute(loopNeedDataMap, new FRBaseObserver<MailAndFundVerifyDataBean>(this) {
            @Override
            protected void onBaseNext(final MailAndFundVerifyDataBean data) {
                FRLog.e("jiang", data.toString());
                if (data.getPoll_status() == 1) {
                    stopRunning();
                    if (fromInfoActivity(data)) return;
                    switch (data.getCode()) {
                        case InfoConstant.VERIFY_STATUS_REAL_NAME_NOT_MATCH://实名不匹配
                            StatusForNotFoundMailActivity.start(getActivity(), InfoConstant.CREDIT_CATE_ID, String.valueOf(data.getCode()), "");
                            break;
                        case InfoConstant.VERIFY_STATUS_MEET_CONDITIONS://满足条件，大额贷
                            LoanCommitActivity.startWithOtherJump(thisActivity(), InfoConstant.CREDIT_CATE_ID, mProductId, mPageSource, mLoanName);
                            break;
                        case InfoConstant.VERIFY_STATUS_DEFAIL://额度不够  小额贷也没有
                            StatusForNonCompliantActivity.start(getActivity(), InfoConstant.CREDIT_CATE_ID, String.valueOf(data.getCode()), "");
                            break;
                        case InfoConstant.VERIFY_STATUS_PETTY_LOAN://小额贷
                            LoanCommitActivity.startWithOtherJump(thisActivity(), InfoConstant.PETTY_LOAN_CATE_ID, mProductId, mPageSource, mLoanName);
                            finish();
                            break;
                        case InfoConstant.VERIFY_STATUS_ONLINE_BANK:
                            showOnLineBankDialog();
                            break;
                    }
                    setCalculateLimitViewGone();
                }
            }
        });
    }

    /**
     * 是否需要跳转网银
     *
     * @param data
     * @return true 跳网银   false  不跳网银
     */
    private boolean NeedJumpOnlineBank(MailAndFundVerifyDataBean data) {
        return InfoConstant.VERIFY_STATUS_ONLINE_BANK == data.getCode();
    }

    private void setCalculateLimitViewGone() {
        mLoadingPll.setVisibility(View.INVISIBLE);
        mCustomStatusView.clearAnimator();
    }

    private boolean fromInfoActivity(MailAndFundVerifyDataBean data) {
        if (TextUtils.isEmpty(mCateId) || TextUtils.isEmpty(mProductId)) {
            if (NeedJumpOnlineBank(data))
                return false;
            setResult(SUCCESS_RETURN_DATA_IMPORT);
            finish();
            return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case StatusForNotFoundMailActivity.NOT_FOUND_MAIN_RETRY://重新验证邮箱
                startMXActiity();
                break;
        }
    }
}
